package com.kly.user.serviceImpl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.api.client.util.Lists;
import com.google.api.client.util.Maps;
import com.google.common.eventbus.AsyncEventBus;
import com.jsoniter.output.JsonStream;
import com.kly.dto.ReduceBenefitsDto;
import com.kly.enums.Benefits;
import com.kly.enums.ParameterTypeEnum;
import com.kly.service.UserVasPurchasesService;
import com.kly.user.chatterService.ChatService;
import com.kly.user.db.dao.*;
import com.kly.user.db.dbo.SumUserMsgDBO;
import com.kly.user.db.dbo.UserMessageCountDBO;
import com.kly.user.db.entity.*;
import com.kly.user.dto.*;
import com.kly.user.dto.chatter.request.ConversationReq;
import com.kly.user.dto.vo.TrafficSourceReq;
import com.kly.user.enums.*;
import com.kly.user.eventbus.ActionEnum;
import com.kly.user.eventbus.Event;
import com.kly.user.mapper.UserMsgMapper;
import com.kly.user.service.*;
import com.kly.user.utils.HttpUtil;
import com.kly.user.utils.ImagePrefixUtils;
import com.kly.user.utils.ServiceUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("userMsgService")
public class UserMsgServiceImpl implements UserMsgService {

    @Resource
    UserMsgMapper userMsgMapper;

    @Resource
    UserMsgDao userMsgDao;
    private static Log logger = LogFactory.getLog(UserMsgServiceImpl.class);
    @Resource
    UserMsgSendTotalDao userMsgSendTotalDao;
    @Resource
    UserMsgSendPreDayDao userMsgSendPreDayDao;
    @Resource
    UserChatterMappingDao userChatterMappingDao;
    @NacosValue(value = "${chatter.url:http://localhost:9105}", autoRefreshed = true)
    private String chatterApiUrl;
    @Resource
    AsyncEventBus asyncEventBus;
    @Resource
    UserMsgForChatterDao userMsgForChatterDao;
    @Resource
    ChatService chatService;
    @Resource
    MessageCmStausDao messageCmStausDao;
    @Resource
    UserDao userDao;
    @NacosValue(value = "${push.enable.switch:false}", autoRefreshed = true)
    private Boolean pushEnable;
    @NacosValue(value = "${addmessage.pushddata.enable}", autoRefreshed = true)
    private boolean pushDataSwitch;
    @Resource
    AdjustService adjustService;
    @Resource
    private AsyncSendMsgService asyncSendMsgService;

    @Resource
    private UserGreetingCommonContentDao userGreetingCommonContentDao;

    @Resource
    private ImNoticeConfigDao imNoticeConfigDao;

    @Autowired
    private MsgModelUnreadDao msgModelUnreadDao;
    @Resource
    UserTrafficSourceService userTrafficSourceService;

    /**
     * @param fromUserId 用户码
     * @param targetId   消息发送对方用户码
     * @param limit      发送条数限制
     */

    @Override
    public List<UserMsgDto> selectByFromUserAndToUser(String fromUserId, String targetId, Integer limit) {
        Map<String, Object> params = ServiceUtils.getParams();
        if (StringUtils.isNotEmpty(fromUserId)) {
            params.put("fromUserCode", fromUserId);
        }
        if (StringUtils.isNotEmpty(targetId)) {
            params.put("toUserCode", targetId);
        }
        params.put("limit", limit);
        List<UserMsgEntity> userMsgEntities = userMsgDao.selectByFromUserAndToUser(params);
        if (CollUtil.isNotEmpty(userMsgEntities)) {
            return userMsgEntities.stream().map(userMsgMapper::toDto).collect(Collectors.toList());
        }
        return null;
    }


    @Override
    public UserMsgDto getUserMsgNum(String fromUserId, String toUserCode) {
        final UserMsgSendTotalEntity userMsgSendTotal = userMsgSendTotalDao.getUserMsgSendTotal(fromUserId, toUserCode);
        if (userMsgSendTotal == null) {
            return null;
        }
        return UserMsgDto.toDto(fromUserId, toUserCode, userMsgSendTotal.getMsgNum());
    }

    @Override
    public List<SumUserMsgDto> listUserMsgByFromUserCode(String fromUserId, String targetId, Integer limit) {
        Map<String, Object> params = ServiceUtils.getParams();
        if (StringUtils.isNotEmpty(fromUserId)) {
            params.put("fromUserCode", fromUserId);
        }
        if (StringUtils.isNotEmpty(targetId)) {
            params.put("toUserCode", targetId);
        }
        params.put("limit", limit);

        List<SumUserMsgDBO> userMsgEntities = userMsgDao.listUserMsgByFromUserCode(params);
        if (CollUtil.isNotEmpty(userMsgEntities)) {
            return userMsgEntities.stream().map(userMsgMapper::toDto).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public List<UserMsgDto> selectTodayMessages(String fromUserId, String targetId, Integer limit) {
//        Map<String, Object> params = ServiceUtils.getParams();
//        if (StringUtils.isNotEmpty(fromUserId)) {
//            params.put("fromUserCode", fromUserId);
//        }
//        if (StringUtils.isNotEmpty(targetId)) {
//            params.put("toUserCode", targetId);
//        }
//        params.put("limit", limit);
//        List<UserMsgEntity> userMsgEntities = userMsgDao.selectTodayMessages(params);
//        if (CollUtil.isNotEmpty(userMsgEntities)) {
//            return userMsgEntities.stream().map(userMsgMapper::toDto).collect(Collectors.toList());
//        }

        final List<UserMsgSendPreDayEntity> userMsgsToday = userMsgSendPreDayDao.listUserMsgToday(fromUserId, targetId);
        if (CollectionUtils.isEmpty(userMsgsToday)) {
            return Lists.newArrayList();
        }
        return userMsgsToday.stream().filter(o -> o.getMsgNum() >= limit).map(o -> {
            UserMsgDto dto = new UserMsgDto();
            dto.setFromUserCode(o.getFromUserCode());
            dto.setToUserCode(o.getToUserCode());
            dto.setMsgNum(o.getMsgNum());
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public int selectByCreateDate(UserConversationDto userConversationDto) {
        Map<String, Object> params = ServiceUtils.getParams();
        params.put("fromUserCode", userConversationDto.getUserCode());
        params.put("toUserCode", userConversationDto.getUserCodeFriend());
        params.put("gmtCreate", userConversationDto.getUserLeaveTime());
        return userMsgDao.selectByCreateDate(params);
    }

    @Override
    public Response<Integer> selectTodayMessageCount(String modelUserCode) {
        return Response.ok(userMsgDao.selectTodayMessageCount(modelUserCode));
    }

    /**
     * 只记录meboo用户发送的消息条数
     */
    @Override
    public String storeMsg(String chatterUserCode, String fromUserCode, String toUserCode) {
        // 获取chatterUserCode
        chatterUserCode = getChatterUserCode(chatterUserCode, fromUserCode, toUserCode);

        // 用户发送消息总数汇总
        storeUserSendMsgTotal(chatterUserCode, fromUserCode, toUserCode);

        // 当日发送消息数汇总
        storeUserMsgPreDay(chatterUserCode, fromUserCode, toUserCode);


        return chatterUserCode;
    }


    @Resource
    UserConversationRecordDao userConversationRecordDao;
    @Resource
    UserVasPurchasesService userVasPurchasesService;
    @Resource
    AppsflyerService appsflyerService;

    private void reduceBenefit(String fromUserCode, String toUserCode, ConversationType conversationType, Benefits benefits, UserMsgSendPreDayEntity dto) {
        final UserConversationRecordEntity userConversation = userConversationRecordDao.getUserConversation(fromUserCode, toUserCode, conversationType.getCode());
        if (userConversation == null) {
            ReduceBenefitsDto reduceBenefits = new ReduceBenefitsDto();
            reduceBenefits.setUserCode(fromUserCode);
            reduceBenefits.setBenefitCode(benefits.getBenefitCode());
            userVasPurchasesService.reduceUserBenefits(reduceBenefits);

            UserConversationRecordEntity entity = new UserConversationRecordEntity();
            entity.setUserCode(fromUserCode);
            entity.setToUserCode(toUserCode);
            entity.setConversationsType(conversationType.getCode());
            entity.setConversationsAttributes(conversationType.getCode());
            entity.setConversationsNumber(dto.getMsgNum());
            entity.setAppsFlyerUid("N/A");
            userConversationRecordDao.insert(entity);

            pushDataToAppsFlyer(fromUserCode, toUserCode, conversationType.getCode());

        } else {
            userConversation.setConversationsNumber(dto.getMsgNum());
            userConversationRecordDao.updateByPrimaryKey(userConversation);
        }


    }

    private void pushDataToAppsFlyer(String userCode, String toUserCode, Integer conversationsType) {
        final HashMap<String, Object> pushData = com.google.common.collect.Maps.newHashMap();
        pushData.put("userCode", userCode);
        pushData.put("toUserCode", toUserCode);
        if (ConversationType.EFFECTIVE_CONVERSATIONS.getCode() == conversationsType) {
            appsflyerService.asyncTraceEvent(AppsFlyerEventDefType.Active_Chat, pushData);
        }
        if (ConversationType.DEEP_CONVERSATIONS.getCode() == conversationsType) {
            appsflyerService.asyncTraceEvent(AppsFlyerEventDefType.Deep_Chat, pushData);
        }
    }

    private void storeUserMsgPreDay(String chatterUserCode, String fromUserCode, String toUserCode) {
        final String today = DateUtil.getDate("yyyyMMdd");
        UserMsgSendPreDayEntity todayRecord = userMsgSendPreDayDao.getUserMsgSendPreDay(Integer.valueOf(today), fromUserCode, toUserCode);

        if (todayRecord == null) {
            todayRecord = new UserMsgSendPreDayEntity();
            todayRecord.setSendDate(Integer.valueOf(today));
            todayRecord.setChatterUserCode(chatterUserCode);
            todayRecord.setFromUserCode(fromUserCode);
            todayRecord.setToUserCode(toUserCode);
            todayRecord.setMsgNum(1);
            userMsgSendPreDayDao.insert(todayRecord);
        } else {
            todayRecord.setMsgNum(todayRecord.getMsgNum() + 1);
            userMsgSendPreDayDao.updateByPrimaryKey(todayRecord);
        }

        if (todayRecord.getMsgNum() > ConversationType.FIRST_CONVERSATION.getSize()) {
            reduceBenefit(fromUserCode, toUserCode, ConversationType.FIRST_CONVERSATION, Benefits.ICE_BREAKING_SESSION, todayRecord);
        }
        if (todayRecord.getMsgNum() > ConversationType.EFFECTIVE_CONVERSATIONS.getSize()) {
            reduceBenefit(fromUserCode, toUserCode, ConversationType.EFFECTIVE_CONVERSATIONS, Benefits.EFFECTIVE_SESSION, todayRecord);
        }
        if (todayRecord.getMsgNum() > ConversationType.DEEP_CONVERSATIONS.getSize()) {
            reduceBenefit(fromUserCode, toUserCode, ConversationType.DEEP_CONVERSATIONS, Benefits.DEEP_SESSION, todayRecord);
        }

        if (todayRecord.getMsgNum() > ConversationType.HUNDRED_CONVERSTIONS.getSize()) {
            reduceBenefit(fromUserCode, toUserCode, ConversationType.HUNDRED_CONVERSTIONS, Benefits.SESSION_MESSAGE_LIMIT, todayRecord);
        }
    }

    private void storeUserSendMsgTotal(String chatterUserCode, String fromUserCode, String toUserCode) {
        final List<UserMsgSendTotalEntity> userMsgSendTotalEntities = userMsgSendTotalDao.queryByUserCode(fromUserCode, toUserCode);
        Integer sendMsgNum = 1;
        if (CollectionUtils.isEmpty(userMsgSendTotalEntities)) {
            UserMsgSendTotalEntity entity = new UserMsgSendTotalEntity();
            entity.setFromUserCode(fromUserCode);
            entity.setToUserCode(toUserCode);
            entity.setChatterUserCode(chatterUserCode);
            entity.setMsgNum(1);
            entity.setMsgNumAfterUnbind(1);
            userMsgSendTotalDao.insert(entity);

            // 用户发送的第一条消息，需要记录一下发送时间及当前model在线状态
            addMessageCMStatusRecord(fromUserCode, toUserCode);
        } else {
            final UserMsgSendTotalEntity existsRecords = userMsgSendTotalEntities.get(0);
            sendMsgNum = existsRecords.getMsgNum() + 1;
            existsRecords.setMsgNum(sendMsgNum);
            existsRecords.setMsgNumAfterUnbind(existsRecords.getMsgNumAfterUnbind() + 1);
            userMsgSendTotalDao.updateByPrimaryKey(existsRecords);
        }

        // 推送有效会话及深度会话到adjust
//        pushDataToAdjust(fromUserCode, toUserCode, sendMsgNum);
        pushDataToAppsFlyerV2(fromUserCode, toUserCode, sendMsgNum);

    }

    /**
     * 推送有效会话及深度会话到adjust
     */
    private void pushDataToAppsFlyerV2(String fromUserCode, String toUserCode, Integer msgNum) {
        try {
            if (pushDataSwitch) {

                final HashMap<String, Object> params = com.google.common.collect.Maps.newHashMap();
                params.put("fromUserCode", fromUserCode);
                params.put("toUserCode", toUserCode);
                params.put("msgNum", msgNum);
                // 埋点分包，pp支持firebase埋点
                String appCode = getAppCode(fromUserCode, toUserCode);
                if (appCode != null) {
                    params.put("appCode", appCode);
                }

                if (msgNum == 31) {
                    params.put("userCode", fromUserCode);
                    appsflyerService.asyncTraceEvent(AppsFlyerEventDefType.Deep_Chat, params);
                } else if (msgNum == 6) {
                    params.put("userCode", fromUserCode);
                    appsflyerService.asyncTraceEvent(AppsFlyerEventDefType.Active_Chat, params);
                }
            }
        } catch (Exception e) {
            logger.error("AddDataToAppsFlyerFailed, fromUserCode:{}, toUserCode:{}", fromUserCode, toUserCode, e);
        }
    }

    /**
     * 获取普通用户的appCode
     */
    private String getAppCode(String fromUserCode, String toUserCode) {
        UserEntity user = userDao.selectActiveUser(fromUserCode);
        if (user != null) {
            return user.getAppCode();
        }
        user = userDao.selectActiveUser(toUserCode);
        if (user != null) {
            return user.getAppCode();
        }
        return null;
    }

    /**
     * 推送有效会话及深度会话到adjust
     */
    private void pushDataToAdjust(String fromUserCode, String toUserCode, Integer msgNum) {
        try {
            if (pushDataSwitch) {

                final HashMap<String, Object> params = com.google.common.collect.Maps.newHashMap();
                params.put("fromUserCode", fromUserCode);
                params.put("toUserCode", toUserCode);
                params.put("msgNum", msgNum);

                if (msgNum == 101) {
                    params.put("userCode", fromUserCode);
                    adjustService.asyncTraceEvent(AdjustEventDefType.Over_limit_Chat, params);
                } else if (msgNum == 31) {
                    params.put("userCode", fromUserCode);
                    adjustService.asyncTraceEvent(AdjustEventDefType.Deep_Chat, params);
                } else if (msgNum == 6) {
                    params.put("userCode", fromUserCode);
                    adjustService.asyncTraceEvent(AdjustEventDefType.Active_Chat, params);
                } else if (msgNum == 2) {
                    params.put("userCode", fromUserCode);
                    adjustService.asyncTraceEvent(AdjustEventDefType.Break_ice_Chat, params);
                }
            }
        } catch (Exception e) {
            logger.error("AddDataToAdjustFailed, fromUserCode:{}, toUserCode:{}", fromUserCode, toUserCode, e);
        }
    }

    private void addMessageCMStatusRecord(String fromUserCode, String toUserCode) {
        try {
            MessageCmStausEntity messageCmStausEntity = new MessageCmStausEntity();
            messageCmStausEntity.setUserCode(fromUserCode);
            messageCmStausEntity.setModelUserCode(toUserCode);
            messageCmStausEntity.setOnlineStatus(userDao.selectByUserCode(toUserCode).getOnline());
            messageCmStausDao.insert(messageCmStausEntity);
        } catch (Exception e) {
            logger.error("addMessageCMStatusRecordFailed, fromUserCode:{}, toUserCode:{}", fromUserCode, toUserCode, e);
        }
    }

    @Override
    public Response storeMsgForChatter(String chatterUserCode, String fromUserCode, String toUserCode) {
        chatterUserCode = getChatterUserCode(chatterUserCode, fromUserCode, toUserCode);
        if (StringUtils.isEmpty(chatterUserCode)) {
            return Response.ok();
        }

        final UserMsgForChatterEntity userMsgForChatter = userMsgForChatterDao.getUserMsgForChatter(chatterUserCode, fromUserCode, toUserCode);
        if (userMsgForChatter == null) {
            UserMsgForChatterEntity entity = new UserMsgForChatterEntity();
            entity.setFromUserCode(fromUserCode);
            entity.setToUserCode(toUserCode);
            entity.setChatterUserCode(chatterUserCode);
            entity.setMsgNum(1);
            userMsgForChatterDao.insert(entity);
        } else {
            userMsgForChatter.setMsgNum(userMsgForChatter.getMsgNum() + 1);
            userMsgForChatterDao.updateByPrimaryKey(userMsgForChatter);
        }

        // 发送当日消息数到mechat
//        pushMsgNumTodayToMechat(chatterUserCode, fromUserCode, toUserCode);

        // 会话等级
//        pushMsgToMechat(fromUserCode, chatterUserCode, toUserCode);

        return Response.ok();
    }

    /**
     * mechat 发送未读消息、会话等级
     */
    private void pushMsgToMechat(String fromUserCode, String chatterUserCode, String toUserCode) {
        if (pushEnable) {
            Map<String, Object> params = new HashMap<>();
            params.put("type", ParameterTypeEnum.PUSH_CHAT_LEVEL.getId());
            params.put("bizCode", PushBizCodeEnum.M20006.getPushBizCode());
            params.put("chatLevel", chatService.getChatLevel(fromUserCode, toUserCode).getData());
            Event event = Event.builder().eventActionEnum(ActionEnum.PUSH_MSG).app(AppEnum.MECHAT).fromUserCode(fromUserCode).toUserCode(toUserCode).chatterUserCode(chatterUserCode).content(com.alibaba.fastjson.JSONObject.toJSONString(params)).build();
            logger.info("====pushMsgToMechat===, event:{}", JSONObject.toJSONString(event));

            asyncEventBus.post(event);
        }
    }

    // 发送消息总数到mechat
    private void pushMsgNumTodayToMechat(String chatterUserCode, String fromUserCode, String toUserCode) {
        try {
            final UserMsgForChatterEntity userMsgForChatter = userMsgForChatterDao.getUserMsgForChatter(chatterUserCode, fromUserCode, toUserCode);
            if (userMsgForChatter == null) {
                return;
            }

            Map<String, String> header = Maps.newHashMap();
            header.put("Content-Type", "application/json");

            Map<String, Object> params = Maps.newHashMap();
            params.put("userCode", fromUserCode);
            params.put("modelUserCode", toUserCode);
            params.put("messageCount", userMsgForChatter.getMsgNum());
            params.put("chatterCode", userMsgForChatter.getChatterUserCode());
            final String response = HttpUtil.postPageBody(chatterApiUrl + "/api/chat/sendMessageNotice", header, JSONObject.toJSONString(params));
            logger.info("用户发送消息数, req:{}, res:{}", JSONObject.toJSONString(params), response);
        } catch (Exception e) {
            logger.error("pushMsgNumTodayToMechat error, chatterUserCode:{}, fromUserCode:{}, toUserCode:{}", chatterUserCode, fromUserCode, toUserCode, e);
        }
    }

    private String getChatterUserCode(String chatterUserCode, String fromUserCode, String toUserCode) {
        if (org.springframework.util.StringUtils.isEmpty(chatterUserCode)) {
            final List<UserChatterMappingEntity> userChatterMappingEntities = userChatterMappingDao.queryByModelUserCode(fromUserCode, toUserCode);
            if (com.fqgj.common.utils.CollectionUtils.isNotEmpty(userChatterMappingEntities)) {
                chatterUserCode = userChatterMappingEntities.get(0).getChatterUserCode();
            }
        }
        return chatterUserCode;
    }


    @Override
    public Response<List<UserMessageCountDto>> selectTodayMessageCountInfo(String chatterCode, String modelUserCode, Integer startCount) {
        return Response.ok(UserMessageCountDBO.toDto(userMsgDao.selectTodayMessageCountInfo(chatterCode, modelUserCode, startCount)));
    }

    @Override
    public Response<List<String>> selectModelCodes(String chatterCode) {
        return Response.ok(userMsgDao.selectModelCodes(chatterCode));
    }

    @Override
    public void sendFlashChatFlag(String fromUseCode, String toUserCode) {


        // 保存一条对方用户的会话（非当前用户）
        final ConversationReq conversationReq = ConversationReq.builder().fromUserCode(fromUseCode).toUserCode(toUserCode).type(1).source(AppEnum.MECHAT.getAppCode()).latestTime(new Date()).conversationType(1).build();
        chatService.storageConversation(conversationReq);

        if (pushEnable) {
            asyncEventBus.post(buildEvent(fromUseCode, toUserCode, "S20005"));
        }
    }

    @Override
    public void sendMessage(String appCode, String targetId, String objectName, String content, String pushContent) {
        if (AppCodeEnum.MEBOO.getAppCode().equals(appCode)) {
            asyncSendMsgService.sendMsg(appCode, targetId, objectName, content, pushContent);
            return;
        }

        final TrafficSourceReq trafficSourceReq = TrafficSourceReq.buildReq(appCode, targetId, null, null, null);
        final Response<TrafficSourceDto> trafficSource = userTrafficSourceService.getTrafficSource(trafficSourceReq);
        if (trafficSource.getData().getTrafficSourceEnum().equals(TrafficSourceEnum.None_Organic)) {
            asyncSendMsgService.sendMsg(appCode, targetId, objectName, content, pushContent);
        }
    }

    @Override
    public Response<List<String>> getGreetingContent(String greetingCode, int limitNum, String appCode) {
        return Response.ok(userGreetingCommonContentDao.getGreetingContent(greetingCode, limitNum, appCode));
    }

    @Override
    public List<Integer> getPopImNums(String appCode) {
        return imNoticeConfigDao.getPopImNums(appCode);
    }

    @Override
    public ImNoticeConfigDto getNoticeConfig(Integer popImNum, String appCode) {
        ImNoticeConfigEntity imNoticeConfigEntity = imNoticeConfigDao.getNoticeConfig(popImNum, appCode);
        if (imNoticeConfigEntity != null) {
            ImNoticeConfigDto imNoticeConfigDto = new ImNoticeConfigDto();
            imNoticeConfigDto.setPopTitle(imNoticeConfigEntity.getPopTitle());
            imNoticeConfigDto.setPopContent(imNoticeConfigEntity.getPopContent());
            imNoticeConfigDto.setPopPicUrl(StringUtils.isNotEmpty(imNoticeConfigEntity.getPopPicUrl()) ? ImagePrefixUtils.getFullImageUrl(imNoticeConfigEntity.getPopPicUrl()) : "");
            imNoticeConfigDto.setPopButton(imNoticeConfigEntity.getPopButton());
            return imNoticeConfigDto;
        }
        return null;
    }


    @Override
    public Integer selectMessageCount(String userCode) {
        return userMsgDao.selectMessageCount(userCode);
    }

    @Override
    public void sendFailPayMessage(String userCode) {
        String message = "Oops, you failed to pay via this current method@Please try another payment method.Google play supports credit card, paypal, google gift card.You can change to another credit card if one doesn't work.\n" + "  If any problem arises, please message our Support Team via email\uD83D\uDCEE: contact@imeboo.com";
        final UserEntity userEntity = userDao.selectByUserCode(userCode);
        asyncSendMsgService.sendMsg(userEntity.getAppCode(), userCode, "RC:InfoNtf", message, message);
    }


    private Event buildEvent(String fromUseCode, String toUserCode, String target) {
        Map<String, Object> params = com.google.common.collect.Maps.newHashMap();
        params.put("type", ParameterTypeEnum.PUSH_MODEL_ONLINE.getId());
        params.put("target", target);
        params.put("online", OnlineStatus.ONLINE_STATUS.getType());
        params.put("flashchatFlag", 1);
        return Event.builder().eventActionEnum(ActionEnum.PUSH_MSG).fromUserCode(fromUseCode).toUserCode(toUserCode).app(AppEnum.MEBOO).content(JSONObject.toJSONString(params)).build();
    }


    @Override
    public Response recordModelSwitchUnreadMsg(MsgUnreadVo msgUnreadVo) {
        logger.info("==recordModelSwitchUnreadMsg 开始记录model切换时的数据==,msgUnreadVo:{}", JsonStream.serialize(msgUnreadVo));

        if (StringUtils.isEmpty(msgUnreadVo.getFromModel()) || StringUtils.isEmpty(msgUnreadVo.getTimestamp()) || msgUnreadVo.getUnreadMsgOfFromModel() == null) {
            return Response.error("invalid params");
        }

        if (msgUnreadVo.getTimestamp().length() != 13) {
            return Response.error("invalid timestamp params");
        }
        Date switchDate = new Date();
        try {
            switchDate = new Date(Long.parseLong(msgUnreadVo.getTimestamp()));
        } catch (NumberFormatException e) {
            logger.error("==recordModelSwitchUnreadMsg 日期转化出错==");
        }

        MsgModelUnreadEntity msgModelUnreadEntity = new MsgModelUnreadEntity().setUnreadMsgNum(msgUnreadVo.getUnreadMsgOfFromModel()).setSwitchTime(switchDate).setModelCode(msgUnreadVo.getFromModel()).setChatterCode(msgUnreadVo.getChatterCode());

        msgModelUnreadDao.insert(msgModelUnreadEntity);
        return Response.ok();
    }
}
